import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { getMyCourses, createCourse, deleteCourse } from '@/services/course';
import { getClasses } from '@/services/class';
import { Course } from '@/types';
import { courseTemplates } from '@/config/courseTemplates';
import '@/styles/pages/courseManage.scss';

const CourseManage = () => {
  const [courses, setCourses] = useState<Course[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState('');
  const [courseName, setCourseName] = useState('');
  const [className, setClassName] = useState('');
  const [selectedClassId, setSelectedClassId] = useState<number | ''>('');
  const [courseDesc, setCourseDesc] = useState('');
  const [error, setError] = useState('');
  const [classes, setClasses] = useState<{id: number, name: string}[]>([]);
  const [classesLoading, setClassesLoading] = useState(false);

  const fetchCourses = async () => {
    try {
      setLoading(true);
      const res = await getMyCourses();
      console.log('获取课程列表响应:', res);
      
      // 处理不同返回格式的数据
      if (res && (res.code === 0 || res.code === 2000)) {
        if (res.data && Array.isArray(res.data.courses)) {
          setCourses(res.data.courses);
          console.log('成功设置课程列表:', res.data.courses);
        } else if (res.data && typeof res.data === 'object') {
          // 尝试从data中提取课程数据
          const extractedCourses = Object.values(res.data).find(Array.isArray);
          if (extractedCourses) {
            setCourses(extractedCourses);
            console.log('成功提取并设置课程列表:', extractedCourses);
          } else {
            setCourses([]);
            console.warn('无法提取课程数据:', res.data);
          }
        } else {
          setCourses([]); // 如果没有数据，设置为空数组
          console.warn('课程数据为空或格式不匹配:', res.data);
        }
      } else {
        console.error('获取课程列表失败:', res.message || res.msg);
        setCourses([]);
      }
    } catch (err) {
      console.error('获取课程列表失败', err);
      setCourses([]);
    } finally {
      setLoading(false);
    }
  };

  // 获取班级列表
  const fetchClasses = async () => {
    try {
      setClassesLoading(true);
      const res = await getClasses();
      
      if (res.code === 0 || res.code === 2000) {
        // 处理班级数据，根据后端返回格式
        if (res.data && Array.isArray(res.data.classes)) {
          setClasses(res.data.classes);
          console.log('成功设置班级列表:', res.data.classes);
        } else if (Array.isArray(res.data)) {
          setClasses(res.data);
          console.log('成功设置班级列表(直接数组):', res.data);
        } else {
          setClasses([]);
          console.warn('班级数据为空或格式不匹配:', res.data);
        }
      } else {
        console.error('获取班级列表失败:', res.message || res.msg);
      }
    } catch (err) {
      console.error('获取班级列表失败', err);
    } finally {
      setClassesLoading(false);
    }
  };

  useEffect(() => {
    fetchCourses();
    fetchClasses();
  }, []);

  // 当预设课程模板改变时，更新课程名称和描述
  const handleTemplateChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const templateId = e.target.value;
    setSelectedTemplate(templateId);
    
    if (templateId) {
      const template = courseTemplates.find(t => t.id === parseInt(templateId));
      if (template) {
        setCourseName(template.name);
        setCourseDesc(template.description);
      }
    }
  };

  // 班级选择变化
  const handleClassChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const classId = e.target.value;
    setSelectedClassId(classId ? parseInt(classId) : '');
    
    // 如果选择了班级，设置班级名称
    if (classId) {
      const selectedClass = classes.find(c => c.id === parseInt(classId));
      if (selectedClass) {
        setClassName(selectedClass.name);
      }
    } else {
      setClassName('');
    }
  };

  // 自定义课程名称输入
  const handleCourseNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setCourseName(e.target.value);
    // 如果用户修改了课程名称，清除选中的模板
    setSelectedTemplate('');
  };

  const handleCreateCourse = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    if (!courseName.trim()) {
      setError('请输入课程名称');
      return;
    }

    if (!selectedClassId) {
      setError('请选择班级');
      return;
    }

    try {
      // 使用班级ID
      const res = await createCourse(courseName, className, courseDesc, selectedClassId as number);
      console.log('创建课程响应:', res);
      
      if (res.code === 0 || res.code === 2000) {
        setCourseName('');
        setClassName('');
        setSelectedClassId('');
        setCourseDesc('');
        setSelectedTemplate('');
        setShowModal(false);
        
        // 创建成功后立即刷新课程列表
        setTimeout(() => {
          fetchCourses();
        }, 500); // 添加短暂延迟，确保后端完成处理
      } else {
        setError(res.message || '创建课程失败');
      }
    } catch (err: any) {
      console.error('创建课程出错:', err);
      setError(err.message || '网络错误，请稍后重试');
    }
  };

  const handleDeleteCourse = async (id: number) => {
    if (window.confirm('确定要删除该课程吗？')) {
      try {
        const res = await deleteCourse(id);
        if (res.code === 0 || res.code === 2000) {
          fetchCourses();
        } else {
          alert(res.message || '删除课程失败');
        }
      } catch (err) {
        console.error('删除课程失败', err);
        alert('网络错误，请稍后重试');
      }
    }
  };

  const resetForm = () => {
    setSelectedTemplate('');
    setCourseName('');
    setClassName('');
    setSelectedClassId('');
    setCourseDesc('');
    setError('');
  };

  const handleOpenModal = () => {
    resetForm();
    setShowModal(true);
  };

  return (
    <div className="course-manage-container">
      <div className="page-header">
        <h1>课程管理</h1>
        <button 
          className="btn btn-primary"
          onClick={handleOpenModal}
        >
          创建课程
        </button>
      </div>

      {loading ? (
        <div className="loading">加载中...</div>
      ) : courses.length > 0 ? (
        <div className="course-list">
          {courses.map((course) => (
            <div className="course-card" key={course.id}>
              <div className="course-card-header">
                <h2>{course.name}</h2>
                <div className="course-actions">
                  <Link 
                    to={`/courses/${course.id}`} 
                    className="btn btn-default"
                  >
                    详情
                  </Link>
                  <button 
                    className="btn btn-danger"
                    onClick={() => handleDeleteCourse(course.id)}
                  >
                    删除
                  </button>
                </div>
              </div>
              <div className="course-card-content">
                <p>{course.description || '暂无描述'}</p>
                <p className="class-name">班级: {course.class_name}</p>
              </div>
              <div className="course-card-footer">
                <span>创建时间: {course.created_at && new Date(course.created_at).toLocaleString()}</span>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="empty-data">
          <p>暂无课程数据</p>
          <button 
            className="btn btn-primary"
            onClick={handleOpenModal}
          >
            创建课程
          </button>
        </div>
      )}

      {/* 创建课程模态框 */}
      {showModal && (
        <div className="modal-overlay">
          <div className="modal-content">
            <div className="modal-header">
              <h2>创建课程</h2>
              <button 
                className="close-btn"
                onClick={() => setShowModal(false)}
              >
                &times;
              </button>
            </div>
            
            {error && <div className="error-message">{error}</div>}
            
            <form onSubmit={handleCreateCourse}>
              <div className="form-item">
                <label htmlFor="courseTemplate">预设课程模板</label>
                <select
                  id="courseTemplate"
                  value={selectedTemplate}
                  onChange={handleTemplateChange}
                >
                  <option value="">请选择或自定义课程</option>
                  {courseTemplates.map(template => (
                    <option key={template.id} value={template.id}>
                      {template.name}
                    </option>
                  ))}
                </select>
              </div>
              
              <div className="form-item">
                <label htmlFor="courseName">课程名称</label>
                <input
                  id="courseName"
                  type="text"
                  value={courseName}
                  onChange={handleCourseNameChange}
                  placeholder="请输入课程名称或选择预设课程"
                />
              </div>
              
              <div className="form-item">
                <label htmlFor="className">班级</label>
                <select
                  id="className"
                  value={selectedClassId}
                  onChange={handleClassChange}
                  disabled={classesLoading}
                >
                  <option value="">请选择班级</option>
                  {classes.map(cls => (
                    <option key={cls.id} value={cls.id}>
                      {cls.name}
                    </option>
                  ))}
                </select>
                {classesLoading && <div className="loading-text">加载班级列表中...</div>}
              </div>
              
              <div className="form-item">
                <label htmlFor="courseDesc">课程描述</label>
                <textarea
                  id="courseDesc"
                  value={courseDesc}
                  onChange={(e) => setCourseDesc(e.target.value)}
                  placeholder="请输入课程描述"
                  rows={4}
                ></textarea>
              </div>
              
              <div className="form-actions">
                <button 
                  type="button" 
                  className="btn btn-default"
                  onClick={() => setShowModal(false)}
                >
                  取消
                </button>
                <button type="submit" className="btn btn-primary">
                  创建
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default CourseManage; 